//
//  NetworkTool.m
//  Kits
//
//  Created by MiaoYe on 15/6/28.
//  Copyright (c) 2015年 Azhuo. All rights reserved.
//

#import "NetworkTool.h"
//#import "UserConfig.h"
//#import "NSString+Encrypt.h"
//#import "OpenUDID.h"
//#import "constantDefinition.h"
@implementation NetworkTool
+ (void)getWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(SuccessBlock)success failed:(FailedBlock)failed{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
   // manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //to do 过滤空数据
        success(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(error);
        NSLog(@"%@ error == \n%@",url,error);
    }];
    
}

+ (void)uploadImageWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(SuccessBlock)success failed:(FailedBlock)failed{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"upload header image success: \n%@",responseObject);
        success(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@ url error == %@",url,error);
        failed(error);
    }];
    
}

+ (void)getInfoWithUrl:(NSString *)url parameters:(NSDictionary *)parameters image:(UIImage *)image success:(SuccessBlock)success failed:(FailedBlock)failed{
    
    NSData *imgData = UIImageJPEGRepresentation(image, 0.1);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:imgData name:@"upfile" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(responseObject);
        
        NSLog(@"%@ success : %@",url,responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failed(error);
        NSLog(@"%@ error: %@",url,error);
    }];
    
}
//jsonData转字典
+ (id)toNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingMutableLeaves
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
//转成数组
+ (id)toArray:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingMutableContainers
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
    
}

//16进制颜色转换

+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
////加盐加密
//+ (NSString *)generateSignByParams:(NSDictionary *)params
//                      commonParams:(NSDictionary *)commonParams
//{
//    NSMutableDictionary  *mParams = [NSMutableDictionary dictionaryWithDictionary:params];
//    [mParams addEntriesFromDictionary:commonParams];
//    
//    NSMutableArray *pairs = [NSMutableArray arrayWithCapacity:0];
//    [mParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
//        [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, obj]];
//    }];
//    
//    //排序
//    [pairs sortUsingSelector:@selector(compare:)];
//    NSString  *sign = [pairs componentsJoinedByString:@"&"];
//    
//    //生成签名
//    NSString  *signStr = [sign stringByAppendingString:LOGIN_DOC_SALT];
//    NSLog(@"签名==== %@",signStr);
//    //MD5加密
//    return [signStr md5];
//}
//
//+ (NSMutableDictionary *)commonParams
//{
//    NSMutableDictionary *commonParams = [NSMutableDictionary dictionaryWithCapacity:0];
//    [commonParams setObject:[OpenUDID value] forKey:@"client"];
//    [commonParams setObject:[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]]
//                     forKey:@"time"];
//    UserConfig *userConfig = [UserConfig sharingUserConfig];
//    
//    if ([userConfig getCurrentUserToken]) {
//        [commonParams setObject:[userConfig getCurrentUserToken] forKey:@"token"];
//    }else{
//        [commonParams setObject:@"" forKey:@"token"];
//    }
//    
//    return commonParams;
//}
//
////时间戳转换
//+ (NSString *)timeFormatted:(int)totalSeconds {
//    NSLog(@"totalSeconds=%i",totalSeconds);
//    NSDate * date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
//    NSString * dateStr = [dateFormatter stringFromDate:date];
////    NSInteger dateNum=[dateStr intValue];
//    return [NSString stringWithFormat:@"%@",dateStr];
//}
//

+(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}


+(NSMutableArray *)parseJSONStringToNSMutableArray:(NSString *)JSONString{
    NSData *JSNData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *responseJson = [NSJSONSerialization JSONObjectWithData:JSNData options:NSJSONReadingMutableLeaves error:nil];
    return responseJson;
}

//检测是否是手机号码
+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,177
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]||7[7]|8[025-9])\\d{10}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    //NSString * CU=@"^1(3|7[(0-2)|7]|5[256]|8[56])\\d{8}$)";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,177
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}



@end
